const express=require('express')
const multer=require('multer')
const path =require('path')
const app=express()
const storage=multer.diskStorage({
  destination:(req,file,cb)=>{
    console.log(file);
    console.log(req);
    cb(null,'uploads')
  },
  filename:(req,file,cb)=>{
    const uniqueSuffix=Date.now()+'-'+Math.round(Math.random()*1E9)
    cb(null,file.fieldname+'-'+uniqueSuffix+path.extname(file.originalname))
  }
})
const upload=multer({storage})
app.post('/',upload.single('img'),(req,res)=>{

 
  res.setHeader('Access-Control-Allow-Origin','null')
  if (!req.file) {
    return res.status(400).json({error:'未选择图片'})
  }

  const imgUrl=`http://localhost:3000/uploads/${req.file.filename}`
  res.json({imgUrl})
 
  
})
app.use('/uploads',express.static(path.join(__dirname,'uploads')))
app.listen(3000,()=>{
  console.log('server is listening');
})